import { reactive, computed, markRaw } from 'vue';
import { getDemos } from '../demoRegistry.js';
import { getDemoSourceCode, getAllDemoSourceFiles } from '../utils/demoUtils.js';
import { clearComponentCache } from '../utils/componentLoader.js';

// 创建初始状态
const state = reactive({
  currentDemo: '',
  isNavigationCollapsed: false,
  showSourceCode: false,
  sourceCode: '',
  sourceCodeFiles: [], // 存储多个源码文件
  activeSourceFile: 0, // 当前激活的源码文件索引
  demos: [], // 初始化为空数组
  demoComponents: {},
  // 添加搜索和过滤相关状态
  searchTerm: '',
  selectedCategory: 'all',
  // 添加加载状态跟踪
  loadingStates: {
    components: {}, // 组件加载状态
    sourceCode: false // 源码加载状态
  },
  // 添加错误状态跟踪
  errorStates: {
    components: {} // 组件加载错误
  },
  // 添加组件加载错误状态
  componentLoadError: null
});

// 定义getters
const currentDemoInfo = computed(() => {
  if (!state.currentDemo) return null;
  const demo = state.demos.find(demo => demo.id === state.currentDemo);
  return demo || null;
});

const formattedSourceCode = computed(() => {
  // 简单的代码格式化，实际项目中可以使用更专业的代码格式化库
  if (!state.sourceCode) return '';
  return state.sourceCode
    .replace(/\t/g, '  ') // 将制表符替换为两个空格
    .trim(); // 去除首尾空白
});

// 获取格式化的源码文件内容
const formattedSourceCodeFiles = computed(() => {
  return state.sourceCodeFiles.map(file => {
    // 如果是Vue文件的拆分部分，需要特殊处理
    if (file.type === 'vue-part') {
      return {
        ...file,
        formattedContent: file.content
          .replace(/\t/g, '  ')
          .trim()
      };
    }
    
    // 其他文件的常规处理
    return {
      ...file,
      formattedContent: file.content
        .replace(/\t/g, '  ')
        .trim()
    };
  });
});

const isComponentLoading = (demoId) => {
  return !!state.loadingStates.components[demoId];
};

const isSourceCodeLoading = () => {
  return state.loadingStates.sourceCode;
};

const getComponentLoadError = (demoId) => {
  return state.errorStates.components[demoId];
};

// 获取所有分类
const categories = computed(() => {
  const categories = [...new Set(state.demos.map(demo => demo.category))];
  return ['all', ...categories];
});

// 获取过滤后的演示示例
const filteredDemos = computed(() => {
  let filtered = state.demos;
  
  // 根据分类过滤
  if (state.selectedCategory !== 'all') {
    filtered = filtered.filter(demo => demo.category === state.selectedCategory);
  }
  
  // 根据搜索词过滤
  if (state.searchTerm) {
    const term = state.searchTerm.toLowerCase();
    filtered = filtered.filter(demo => 
      demo.name.toLowerCase().includes(term) || 
      demo.description.toLowerCase().includes(term) ||
      demo.id.toLowerCase().includes(term)
    );
  }
  
  return filtered;
});

// 定义mutations
const mutations = {
  setCurrentDemo(demoId) {
    state.currentDemo = demoId;
    
    // 更新URL
    const url = new URL(window.location);
    url.searchParams.set('demo', demoId);
    window.history.pushState({}, '', url);
  },
  
  toggleNavigation() {
    state.isNavigationCollapsed = !state.isNavigationCollapsed;
  },
  
  setShowSourceCode(show) {
    state.showSourceCode = show;
  },
  
  setSourceCode(code) {
    state.sourceCode = code;
  },
  
  // 设置源码文件列表
  setSourceCodeFiles(files) {
    state.sourceCodeFiles = files;
    state.activeSourceFile = 0; // 默认激活第一个文件
  },
  
  // 设置当前激活的源码文件
  setActiveSourceFile(index) {
    state.activeSourceFile = index;
  },
  
  setDemoComponent(demoId, component) {
    // Use markRaw to prevent Vue from making the component reactive
    state.demoComponents[demoId] = markRaw(component);
  },
  
  // 添加设置组件加载状态的mutation
  setComponentLoading(demoId, loading) {
    state.loadingStates.components[demoId] = loading;
  },
  
  // 添加设置源码加载状态的mutation
  setSourceCodeLoading(loading) {
    state.loadingStates.sourceCode = loading;
  },
  
  // 添加设置组件错误状态的mutation
  setComponentLoadError(demoId, error) {
    state.errorStates.components[demoId] = error;
  },
  
  // 添加设置组件加载错误的mutation
  setComponentLoadErrorMessage(error) {
    state.componentLoadError = error;
  },
  
  // 添加设置搜索词的mutation
  setSearchTerm(term) {
    state.searchTerm = term;
  },
  
  // 添加设置分类的mutation
  setSelectedCategory(category) {
    state.selectedCategory = category;
  },
  
  // 添加设置演示数据的mutation
  setDemos(demos) {
    state.demos = demos;
  },
  
  // 添加清除缓存的mutation
  clearCache() {
    // 清除组件缓存
    clearComponentCache();
    state.demoComponents = {};
    
    // 清除加载状态
    Object.keys(state.loadingStates.components).forEach(key => {
      delete state.loadingStates.components[key];
    });
    
    // 清除错误状态
    Object.keys(state.errorStates.components).forEach(key => {
      delete state.errorStates.components[key];
    });
    
    state.loadingStates.sourceCode = false;
    state.componentLoadError = null;
  }
};

// 创建actions
const actions = {
  selectDemo(demoId) {
    mutations.setCurrentDemo(demoId);
  },
  
  toggleNavigation() {
    mutations.toggleNavigation();
  },
  
  async loadSourceCode(demoId) {
    // 如果已经在加载，避免重复请求
    if (state.loadingStates.sourceCode) {
      return;
    }
    
    try {
      mutations.setSourceCodeLoading(true);
      mutations.setSourceCode('Loading source code...');
      mutations.setShowSourceCode(true);
      const code = await getDemoSourceCode(demoId);
      mutations.setSourceCode(code);
    } catch (error) {
      mutations.setSourceCode(`Error loading source code: ${error.message}`);
    } finally {
      mutations.setSourceCodeLoading(false);
    }
  },
  
  // 加载所有相关源码文件
  async loadAllSourceCodeFiles(demoId) {
    // 如果已经在加载，避免重复请求
    if (state.loadingStates.sourceCode) {
      return;
    }
    
    try {
      mutations.setSourceCodeLoading(true);
      mutations.setSourceCode('Loading source code...');
      mutations.setShowSourceCode(true);
      const files = await getAllDemoSourceFiles(demoId);
      mutations.setSourceCodeFiles(files);
    } catch (error) {
      mutations.setSourceCode(`Error loading source code: ${error.message}`);
    } finally {
      mutations.setSourceCodeLoading(false);
    }
  },
  
  // 切换当前激活的源码文件
  switchSourceFile(index) {
    mutations.setActiveSourceFile(index);
  },
  
  closeSourceCode() {
    mutations.setShowSourceCode(false);
  },
  
  async loadDemoComponent(demoId) {
    // 如果组件已加载，直接返回
    if (state.demoComponents[demoId]) {
      return state.demoComponents[demoId];
    }
    
    // 如果已经在加载，避免重复请求
    if (state.loadingStates.components[demoId]) {
      // 返回一个Promise以等待加载完成
      return new Promise((resolve, reject) => {
        const checkComponentLoaded = () => {
          if (state.demoComponents[demoId]) {
            resolve(state.demoComponents[demoId]);
          } else if (state.errorStates.components[demoId]) {
            reject(new Error(`Failed to load component: ${state.errorStates.components[demoId]}`));
          } else if (!state.loadingStates.components[demoId]) {
            // 如果不再处于加载状态但组件未加载成功，尝试重新加载
            this.loadDemoComponent(demoId)
              .then(resolve)
              .catch(reject);
          } else {
            // 继续等待
            setTimeout(checkComponentLoaded, 100);
          }
        };
        
        // 开始检查组件加载状态
        checkComponentLoaded();
      });
    }
    
    // 查找并加载组件
    const demo = state.demos.find(d => d.id === demoId);
    if (!demo) {
      const errorMessage = `Demo component not found: ${demoId}`;
      console.error(errorMessage);
      mutations.setComponentLoadError(demoId, errorMessage);
      throw new Error(errorMessage);
    }
    
    try {
      // 清除之前的错误状态
      mutations.setComponentLoadError(demoId, null);
      mutations.setComponentLoading(demoId, true);
      
      // 使用正确的路径加载组件
      const componentModule = await import(`../${demo.component.replace('./', '')}`);
      
      if (!componentModule.default) {
        const errorMessage = `Component not found in module: ${demo.component}`;
        console.error(errorMessage);
        mutations.setComponentLoadError(demoId, errorMessage);
        throw new Error(errorMessage);
      }
      
      const component = componentModule.default;
      mutations.setDemoComponent(demoId, component);
      return component;
    } catch (error) {
      const errorMessage = `Error loading demo component ${demoId}: ${error.message}`;
      console.error(errorMessage, error);
      mutations.setComponentLoadError(demoId, errorMessage);
      throw error;
    } finally {
      mutations.setComponentLoading(demoId, false);
    }
  },
  
  // 添加搜索相关的actions
  setSearchTerm(term) {
    mutations.setSearchTerm(term);
  },
  
  setSelectedCategory(category) {
    mutations.setSelectedCategory(category);
  },
  
  // 加载演示数据
  async loadDemos() {
    const demos = getDemos();
    mutations.setDemos(demos);
  },
  
  // 添加清除缓存的action
  clearAllCache() {
    mutations.clearCache();
  }
};

// 初始化当前演示示例（从URL参数获取）
const urlParams = new URLSearchParams(window.location.search);
const initialDemo = urlParams.get('demo');

// 加载演示数据
async function initializeDemos() {
  try {
    // 等待数据加载完成
    const demos = await getDemos(); // 直接使用导入的函数
    mutations.setDemos(Array.isArray(demos) ? demos : []);
    
    if (initialDemo && Array.isArray(demos) && demos.some(demo => demo.id === initialDemo)) {
      mutations.setCurrentDemo(initialDemo);
    } else if (Array.isArray(demos) && demos.length > 0) {
      // 默认选择第一个演示
      mutations.setCurrentDemo(demos[0].id);
    }
  } catch (error) {
    console.error('Failed to initialize demos:', error);
    // 即使加载失败也设置空的演示列表，避免无限等待
    mutations.setDemos([]);
  }
}

// 确保在下一次事件循环中初始化演示数据
setTimeout(() => {
  initializeDemos();
}, 0);

// 导出store
export default {
  state,
  // Getters
  get currentDemoInfo() { return currentDemoInfo.value; },
  get formattedSourceCode() { return formattedSourceCode.value; },
  get formattedSourceCodeFiles() { return formattedSourceCodeFiles.value; },
  get activeSourceFile() { return state.activeSourceFile; },
  isComponentLoading,
  isSourceCodeLoading,
  getComponentLoadError,
  get categories() { return categories.value; },
  get filteredDemos() { return filteredDemos.value; },
  // Mutations and actions
  ...mutations,
  ...actions
};